package com.rimi.bbs.controller;


import com.rimi.bbs.bean.Card;
import com.rimi.bbs.bean.JsonResult;
import com.rimi.bbs.bean.Replies;
import com.rimi.bbs.service.CardService;
import com.rimi.bbs.service.RepliesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jerry
 * @since 2019-02-24
 */
@RestController
@RequestMapping("/replies")
public class RepliesController {

    @Autowired
    private RepliesService repliesService;

    @Autowired
    private CardService cardService;

    @PostMapping("/accept")
    public Object caiNa(Integer cardId,Integer repliesId){
        //验证该帖是否已经别采纳
        Card card = cardService.getById(cardId);
        if(card.getCardRepliesStatus()==2){
            return JsonResult.error("该帖已有采纳");
        }
        boolean b = repliesService.updateById(new Replies().setRepliesId(repliesId).setRepliesStatus(2));
        if(!b){
            return JsonResult.error("采纳失败");
        }
        //修改帖子的状态为已有采纳
        boolean b1 = cardService.updateById(new Card().setCardId(cardId).setCardRepliesStatus(2));
        if(!b1){
            return JsonResult.error("采纳失败,请重新页面重试");
        }
        return JsonResult.ok("采纳成功");
    }


    /**
     * @param ok  true 为取消点赞  false  点赞
     * @param repliesId 帖子ID
     * @param userId 点赞人ID
     * @return
     * 回帖功能
     * 完成增加点赞量
     * 后续需要添加点赞表 才能处理 取消点赞与限制点赞人数
     */
    @PostMapping("/zan")
    public Object jieDaZan(String ok,Integer repliesId,Integer userId){
        Replies replies = repliesService.getById(repliesId);
        if(replies==null){
            return JsonResult.error("该回复已被删除");
        }
        boolean b = repliesService.updateById(replies.setRepliesPraiseNumber(replies.getRepliesPraiseNumber() + 1));
        if(b){
            return JsonResult.ok("点赞成功");
        }
        return JsonResult.error("点赞失败，请刷新页面重试");
    }


    /**
     * @param replies
     * @return
     * 回帖
     *  还须添加消息通知功能
     */
    @PostMapping("/reply")
    @ResponseBody
    public Object reply(Replies replies){
        //回复帖子
        boolean save = repliesService.save(replies.setRepliesTime(LocalDateTime.now()));
        if(save){
            Card card = cardService.getById(replies.getCardId());
            cardService.updateById(new Card().setCardId(replies.getCardId()).setCardAnswerNumber(card.getCardAnswerNumber()+1));
            return JsonResult.ok("回复成功").put("content",replies.getRepliesContent());
        }
        return JsonResult.error("回复失败,请重试");
    }
}

